package main.java.com.imooc;

import java.io.*;
import java.net.Socket;

/**
 * 服务器端县城处理类
 * Created by 95577 on 2018/6/21.
 */
public class ServerThread extends  Thread {

    // 和本线程相关的Socket
    Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    // 线程执行操作，相应客户端的请求
    public void run() {


        InputStream is = null; // 字节流输入
        PrintWriter pw = null;
        OutputStream os = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        try {
            // 3: 获取输入流，读取客户端信息
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String info = null;
            // 循环读取客户端的信息
            while ((info = br.readLine()) != null) {
                System.out.println("------------------------我是服务器，客户端说" + info);
            }
            socket.shutdownInput(); // 关闭输入流


            // 4:获取输出流，相应客户端输出请求
            os = socket.getOutputStream();
            pw = new PrintWriter(os);
            pw.write("欢迎您");
            pw.flush(); // 将缓存输出

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

            // 5：关闭相应资源
            if (pw != null)
                pw.close();
            if (os != null)
                os.close();
            if (br != null)
                br.close();
            if (isr != null)
                isr.close();
            if (is != null)
                is.close();
            if (socket != null)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
